package com.iot.system.core.impl;

import com.iot.common.enums.DeviceStatusType;
import com.iot.common.utils.bean.BeanUtils;
import com.iot.system.core.CoreDeviceStateService;
import com.iot.system.domain.DeviceDetails;
import com.iot.system.domain.DeviceState;
import com.iot.system.domain.DeviceStateLogs;
import com.iot.system.domain.vo.DeviceStateVo;
import com.iot.system.service.IDeviceDetailsService;
import com.iot.system.service.IDeviceStateService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CoreDeviceStateServiceImpl implements CoreDeviceStateService {

    @Resource
    private IDeviceStateService iDeviceStateService;

    @Resource
    private IDeviceDetailsService iDeviceDetailsService;


    @Override
    public int insertDeviceState(DeviceState deviceState) {
        return 0;
    }

    @Override
    public List<DeviceStateVo> selectDeviceStateList(DeviceState deviceState) {
        List<DeviceState> list = iDeviceStateService.selectDeviceStateList(deviceState);
        if (CollectionUtils.isEmpty(list)){
            return new ArrayList<>();
        }
        Map<Long, DeviceDetails> detailsMap = getLongDeviceDetailsMap(list);

        List<DeviceStateVo> deviceStateVos = list.stream().map(item -> {
            DeviceStateVo deviceStateVo = new DeviceStateVo();
            BeanUtils.copyProperties(item, deviceStateVo);
            if (detailsMap.containsKey(item.getDeviceId())) {
                deviceStateVo.setDeviceName(detailsMap.get(item.getDeviceId()).getDeviceName());
                deviceStateVo.setDeviceTemsCode(detailsMap.get(item.getDeviceId()).getDeviceTemsCode());
            }
            DeviceStatusType deviceStatusType = DeviceStatusType.fromNumber(Integer.valueOf(item.getStateType()));
            deviceStateVo.setStateType(deviceStatusType.getNumber());
            return deviceStateVo;
        }).collect(Collectors.toList());

        return deviceStateVos;
    }

    private Map<Long, DeviceDetails> getLongDeviceDetailsMap(List<DeviceState> stateLogsList) {
        List<Long> deviceIds = stateLogsList.stream().map(DeviceState::getDeviceId).collect(Collectors.toList());
        List<DeviceDetails> deviceDetails = iDeviceDetailsService.selectDeviceNameAndTemsCodeByIds(deviceIds);
        Map<Long, DeviceDetails> detailsMap = deviceDetails.stream().collect(Collectors.toMap(item -> item.getId(), item -> item));
        return detailsMap;
    }

    @Override
    public String selectDeviceStateById(Long id) {
        return null;
    }

    @Override
    public int updateDeviceState(DeviceState deviceState) {
        return 0;
    }

    @Override
    public int deleteDeviceStateByIds(Long[] ids) {
        return 0;
    }
}
